import router from '.'
import { loadingRouter } from './routeInit'

export const guard = () => {
    router.beforeEach(async (to, from, next) => {

        const token = localStorage.getItem('token')

        // 跳转的是否是登录页
        const isToLoginPage = to.path === '/login'

        if (token) {
            if (isToLoginPage) {
                next(typeof to.query.to === 'string' ? to.query.to : '/')
                return
            }

            if (to.matched.length === 0) {
                await loadingRouter()
                const isExit = router.getRoutes().some(item => item.path === to.path)
                if (isExit) {
                    next({ ...to, replace: true })
                } else {
                    next('/404')
                }
            } else {
                next()
            }
            return
        }

        // 未登录状态 是否跳转登录页
        if (isToLoginPage) {
            next()
        } else {
            if (to.meta && to.meta?.auth) {
                next({ path: '/login', query: { to: to.fullPath } })
            } else {
                next()
            }
        }
    })
}
